package com.service.screenWeb.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.utils.IdUtil;
import com.service.config.utils.ModelMapperUtil;
import com.service.screenWeb.dao.AssemblyDao;
import com.service.screenWeb.dao.ScreenUserDao;
import com.service.screenWeb.dto.CheckTenantDto;
import com.service.screenWeb.dto.ProgrammeInfoDto;
import com.service.screenWeb.dto.ScreenUserDto;
import com.service.screenWeb.dto.SiteDto;
import com.service.screenWeb.entity.Assembly;
import com.service.screenWeb.entity.ProgrammeInfo;
import com.service.screenWeb.entity.ScreenUser;
import com.service.screenWeb.service.ProgrammeInfoService;
import com.service.screenWeb.service.ScreenUserService;
import com.service.screenWeb.task.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.service.config.constant.ApiUrlConstants.*;

/**
 * 大屏用户表(ScreenUser)表服务实现类
 *
 * @author makejava
 * @since 2021-03-29 15:42:46
 */
@Service("screenUserService")
@Slf4j
public class ScreenUserServiceImpl implements ScreenUserService {
    @Resource
    private ScreenUserDao screenUserDao;
    @Resource
    RestTemplate restTemplate;

    @Resource
    private AssemblyDao assemblyDao;
    @Autowired
    ScheduleService scheduleService;
    @Resource
    ProgrammeInfoService programmeInfoService;

    /**
     * 获取token
     *
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public String getToken(String username, String password, HttpHeaders requestHeaders, String domain) {
        //获取token
        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        try {
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST + domain + CLOUD_CAMPUS_TOKEN_URL, HttpMethod.POST, requestEntity, JSONObject.class);
            return response.getBody().getJSONObject("data").getString("token_id");
        } catch (Exception e) {
            log.error("debug Token ==>" + e.getMessage());
            return null;
        }
    }
    /**
     * 获取站点site
     *
     * @param requestHeaders
     * @return
     */
    public List<SiteDto> getSites(HttpHeaders requestHeaders, String domain) {
        //获取站点
        boolean flag = true;
        int pageIndex = 1;
        List<SiteDto> siteDtos = new ArrayList<>();
        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + SITE_URL + pageIndex, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = response.getBody().getJSONArray("data");
                if (!data.isEmpty()) {
                    siteDtos.addAll(data.toJavaList(SiteDto.class));
                    pageIndex++;
                } else {
                    flag = false;
                }
            }
            return siteDtos;
        } catch (Exception e) {
            log.error("debug getSites ==>" + e.getMessage());
            return null;
        }
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ScreenUser queryById(String id) {
        return this.screenUserDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<ScreenUser> queryAllByLimit(int offset, int limit) {
        return this.screenUserDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param screenUser 实例对象
     * @return 实例对象
     */
    @Override
    public ScreenUser insert(ScreenUser screenUser) {
        this.screenUserDao.insert(screenUser);
        return screenUser;
    }

    /**
     * 修改数据
     *
     * @param screenUser 实例对象
     * @return 实例对象
     */
    @Override
    public ScreenUser update(ScreenUser screenUser) {
        screenUser.setModelId(IdUtil.getStringId());
        this.screenUserDao.update(screenUser);
        return this.queryById(screenUser.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.screenUserDao.deleteById(id) > 0;
    }

    /**
     * 校验云管api
     * @param checkTenantDto
     * @param userId
     * @return
     */
    @Override
    public Map check(CheckTenantDto checkTenantDto, String userId) {
        HashMap map = new HashMap();
        ScreenUser screenUser = new ScreenUser();
        screenUser.setName(checkTenantDto.getUsername());
        List<ScreenUser> screenUsers = screenUserDao.queryAll(screenUser);
        //该账号是否存在
        if (screenUsers.size() > 0) {
            map.put("errorMsg","关联华为云管理账号已存在");
        }else {
            HttpHeaders requestHeaders = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            requestHeaders.setContentType(type);
            requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
            String token = getToken(checkTenantDto.getUsername(), checkTenantDto.getPassword(), requestHeaders, checkTenantDto.getDomain());
            if (token == null) {
                map.put("errorMsg", "华为云管理账号不存在");
            } else {
                //获取站点
                requestHeaders.add("X-AUTH-TOKEN", token);
                List<SiteDto> sites = getSites(requestHeaders, checkTenantDto.getDomain());
                if (sites != null && sites.size() > 0) {
                    return map;
                }
                map.put("errorMsg", "该账号没有权限调用api");
            }
        }
        return map;
    }

    @Transactional
    @Override
    public List<ScreenUser> insertOrUpdate(ScreenUser strictMap, String userId) throws Exception {
        ScreenUser screenUser = new ScreenUser();
        screenUser.setTenantName(strictMap.getTenantName());
        screenUser.setUserId(userId);
        screenUser.setDomain(strictMap.getDomain());
        List<ScreenUser> screenUsers = screenUserDao.queryAll(screenUser);
        if (screenUsers.size() > 0) {
            return screenUsers;
        } else {
            strictMap.setId(IdUtil.getStringId());
            strictMap.setUserId(userId);
            strictMap.setModelId("1");
            strictMap.setStatus(true);
            screenUserDao.insert(strictMap);
            ProgrammeInfo programmeInfo = new ProgrammeInfo();
            programmeInfo.setUserId(userId);
            programmeInfoService.queryAll(programmeInfo, userId);
            scheduleService.getLoginUserDispose(strictMap);
            return null;
        }
    }

    @Override
    public void serviceStatusBind(String screen_user_id, Boolean status, String userId, String domain) {
        ScreenUser screenUser1 = new ScreenUser();
        screenUser1.setUserId(userId);
        screenUser1.setDomain(domain);
        List<ScreenUser> screenUsers = screenUserDao.queryAll(screenUser1);
        List<ScreenUser> collect = screenUsers.stream().filter(screenUser2 -> !screenUser2.getId().equals(screen_user_id)).collect(Collectors.toList());
        collect.stream().forEach(screenUser2 -> {
            if (status) {
                screenUser2.setStatus(false);
            }
        });
        List<ScreenUser> collect1 = screenUsers.stream().filter(screenUser2 -> screenUser2.getId().equals(screen_user_id)).collect(Collectors.toList());
        collect1.stream().forEach(screenUser -> {
            screenUser.setUserId(userId);
            screenUser.setId(screen_user_id);
            screenUser.setStatus(status);
        });
        screenUserDao.insertOrUpdateBatch(screenUsers);
    }

    @Override
    public void updateApiAccount(ScreenUser strictMap) {
        screenUserDao.update(strictMap);
    }

    @Override
    public List<ScreenUserDto> queryAll(String userId) {
        ScreenUser screenUser = new ScreenUser();
        screenUser.setUserId(userId);
        List<ScreenUser> list = screenUserDao.queryAll(screenUser);
        List<ScreenUserDto> screenUserDtoList = ModelMapperUtil.strictMapList(list, ScreenUserDto.class);
        return screenUserDtoList;
    }

    @Override
    public void updateName(String userId, String name) {
        ScreenUser screenUser = new ScreenUser();
        screenUser.setName(name);
        screenUser.setUserId(userId);
    }


}
